(function(jQuery,window){
	var select = function(setting){
		this.options = setting.provinces;
		this.arg1 = setting.provinceId; //省
		this.arg2 = setting.cityId; //市
		this.arg3 = setting.areaId; //区
		this.arg4 = setting.provinceCode; //省编码
		this.arg5 = setting.cityCode; //市编码
		this.arg6 = setting.areaCode; //区编码
		this.init(this.options,this.arg1,this.arg4);
		this.changeEvent(this.arg1,this.arg2,this.arg3);
	}
	
	select.prototype = {
		init:function(options,arg1,code){
			var that = this;
			var result = null;
			var flag = null;
			$.each(options,function(index,value){
				if(code && code == value.code){
					var optionDom = "<option value='" + value.code + "' "+"index=" + index + " selected='selected'>" + this.name + "</option>";
					result = value.children;
					if(arg1 == 's_city'){
						flag = 'area';
					}
				}else{
					var optionDom = "<option value='" + value.code + "' "+"index=" + index + ">" + this.name + "</option>";
				}
				$('#'+arg1).append(optionDom);
			});
			if(result){
				if(!flag){
					that.init(result,that.arg2,that.arg5);
				}else if(flag == 'area'){
					that.init(result,that.arg3,that.arg6);
				}
			}
		},
		clear:function(arg){
			$('#'+arg).empty();
			$('#'+arg).append('<option value="" selected="selected">请选择</option>')
		},
		changeEvent:function(arg1,arg2,arg3,arg4,arg5){
			var that = this;
			$('#'+arg1).bind('change',function(){
				var p_index = $('#'+arg1).children("option:selected").attr('index');
				var children = [];
				if(p_index){
					children = that.options[p_index].children;
				}
				that.clear(arg2);
				that.clear(arg3);
				that.init(children,arg2);
			});
			$('#'+arg2).bind('change',function(){
				var p_index = $('#'+arg1).children("option:selected").attr('index');
				var c_index = $('#'+arg2).children("option:selected").attr('index');
				var children = [];
				if(p_index && c_index){
					children = that.options[p_index].children[c_index].children;
				}
				that.clear(arg3);
				that.init(children,arg3);
			});
		}
	}
	
	$.fn.extend({
		initProvince:function(setting){
			setting.provinceId = this.attr('id');
			new select(setting);
		}
	});
	
})(jQuery,window);
